<?php

namespace app\common\model;

use think\facade\Cache;
use ffhome\frame\model\BaseModel;
use think\facade\Db;

class BaseArea extends BaseModel
{
    const MODEL_NAME = 'base_area';
    /**
     * 省份
     */
    const T_PROVINCE = 'PROVINCE';
    /**
     * 城市
     */
    const T_CITY = 'CITY';
    /**
     * 县级市
     */
    const T_TOWN = 'TOWN';

    public static function getAreaByParent($type, $parentId = ''): array
    {
        if (empty($type)) {
            return [];
        }
        $cacheName = "area_list_by_type_{$type}_parent_{$parentId}";
        $list = Cache::get($cacheName);
        if (empty($list)) {
            $where = ['type' => $type];
            if (!empty($parentId)) {
                $where['parent_id'] = $parentId;
            }
            $list = Db::name(self::MODEL_NAME)->field('id,name')->where($where)->order('id')
                ->select()->toArray();
            Cache::tag(self::MODEL_NAME)->set($cacheName, $list);
        }
        return $list;
    }
}